package controllers

import (
	"HomeMaterialManagementSystem/db"
	"HomeMaterialManagementSystem/models"
	"fmt"
	"log"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func itemHandler(c *gin.Context) {
	if c.Request.Method == http.MethodGet {
		id := c.Query("id")
		if id == "" {
			now := time.Now()
			c.HTML(http.StatusOK, "item.html", gin.H{
				"item":     models.Item{CreateDate: &now, ExpireDate: &now, Amount: 1, Source: "线下"},
				"username": c.MustGet("username").(string),
				"title":    "新增",
			})
			return
		} else {
			orm := db.GetORM()
			item := models.Item{}
			orm.Where("id=?", id).Where("hide=0").First(&item)
			c.HTML(http.StatusOK, "item.html", gin.H{
				"item":     item,
				"username": c.MustGet("username").(string),
				"title":    item.ProductName,
			})
			return
		}
	} else if c.Request.Method == http.MethodPost {
		item := models.Item{
			Hide: false,
		}
		item.ID, _ = strconv.ParseInt(c.Request.FormValue("ID"), 10, 64)
		item.Amount, _ = strconv.ParseInt(c.Request.FormValue("Amount"), 10, 64)
		item.Price, _ = strconv.ParseFloat(c.Request.FormValue("Price"), 64)
		s, _ := strconv.ParseInt(c.Request.FormValue("Status"), 10, 64)
		item.Status = int(s)
		item.ProductName = c.Request.FormValue("ProductName")
		item.BrandName = c.Request.FormValue("BrandName")
		item.Desc = c.Request.FormValue("Desc")
		item.Source = c.Request.FormValue("Source")
		item.SearchContent = fmt.Sprintf("%s//%s//%s", item.BrandName, item.ProductName, item.Desc)
		t, err := time.Parse("2006-01-02", c.Request.FormValue("ExpireDate"))
		log.Printf("%+v", t)
		item.ExpireDate = &t
		if err != nil {
			item.ExpireDate = nil
		}
		t1, err := time.Parse("2006-01-02", c.Request.FormValue("CreateDate"))
		item.CreateDate = &t1
		if err != nil {
			item.CreateDate = nil
		}
		t2, err := time.Parse("2006-01-02", c.Request.FormValue("DestroyDate"))
		item.DestroyDate = &t2
		if err != nil {
			item.DestroyDate = nil
		}
		// 数据校验

		if item.ProductName == "" || item.BrandName == "" {
			c.HTML(http.StatusOK, "item.html", gin.H{
				"item":     item,
				"username": c.MustGet("username").(string),
				"title":    item.ProductName,
			})
			return
		}

		// log.Printf("%+v\n", item)
		r := db.GetORM().Debug().Save(&item)
		if r.Error != nil {
			c.Redirect(http.StatusFound, "/item")
		}
		c.Redirect(http.StatusFound, "/items")

	} else if c.Request.Method == http.MethodDelete {
		id := c.Query("id")
		orm := db.GetORM()
		item := models.Item{}
		orm.Where("id=?", id).Where("hide=0").First(&item)
		if item.ID == 0 {
			c.JSON(http.StatusOK, gin.H{})
			return
		}
		item.Hide = true
		orm.Save(&item)
		c.Redirect(http.StatusFound, "/items")
	} else {
		c.JSON(http.StatusMethodNotAllowed, gin.H{})
	}
}

func itemsHandler(c *gin.Context) {
	pageNum, _ := strconv.ParseInt(c.Request.FormValue("page"), 10, 64)
	if pageNum == 0 {
		pageNum = 1
	}

	pageSize, _ := strconv.ParseInt(c.Request.FormValue("pagesize"), 10, 64)
	if pageSize == 0 {
		pageSize = 10
	}

	searchText := c.Request.FormValue("searchtext")

	items := []models.Item{}
	var total int64
	if searchText != "" {
		// Where("name LIKE ?", "%jin%")
		db.GetORM().Where("hide=?", 0).Where("`status`<?", 4).Where("search_content LIKE ?", fmt.Sprintf("%%%s%%", searchText)).Offset(int((pageNum - 1) * pageSize)).Limit(int(pageSize)).Find(&items)
		db.GetORM().Model(&models.Item{}).Where("hide=?", 0).Where("`status`<?", 4).Where("search_content LIKE ?", fmt.Sprintf("%%%s%%", searchText)).Count(&total)
	} else {
		db.GetORM().Where("hide=?", 0).Where("`status`<?", 4).Offset(int((pageNum - 1) * pageSize)).Limit(int(pageSize)).Find(&items)
		db.GetORM().Model(&models.Item{}).Where("hide=?", 0).Where("`status`<?", 4).Count(&total)
	}

	pages := []map[string]int{}
	maxPage := total/int64(pageSize) + 1
	for i := 1; int64(i) <= total/int64(pageSize)+1; i++ {
		pages = append(pages, map[string]int{"value": i})
	}
	prev := pageNum - 1
	next := pageNum + 1
	if maxPage < next {
		next = 0
	}

	log.Printf("%+v", gin.H{
		"page":        pageNum,
		"page_size":   pageSize,
		"prev":        prev,
		"next":        next,
		"pages":       pages,
		"max_page":    maxPage,
		"username":    c.MustGet("username").(string),
		"title":       "物品清单",
		"search_text": searchText,
		"total":       total,
	})

	c.HTML(http.StatusOK, "items.html", gin.H{
		"items":       items,
		"page":        pageNum,
		"page_size":   pageSize,
		"prev":        prev,
		"next":        next,
		"pages":       pages,
		"max_page":    maxPage,
		"username":    c.MustGet("username").(string),
		"title":       "物品清单",
		"search_text": searchText,
		"total":       total,
	})
}
